﻿using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;

namespace ibba.src.sl.componentes
{
    [ContentProperty("Cases")]
    public class SwitchControl: Control
    {
        private ContentPresenter _content;
        private Binding _binding;
        private SwitchConverter _converter;

        public SwitchControl()
        {
            this.DefaultStyleKey = typeof(SwitchControl);

            _converter = new SwitchConverter();
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _content = GetTemplateChild("Content") as ContentPresenter;
            UpdateBindings();
        }

        #region Properties

        public Binding Binding
        {
            get { return _binding; }
            set
            {
                if (value != _binding)
                {
                    _binding = value;

                    if (_binding != null)
                    {
                        _binding.Converter = _converter;
                    }

                    UpdateBindings();
                }
            }
        }

        public SwitchCaseCollection Cases
        {
            get { return _converter.Cases; }
        }

        public object Else
        {
            get { return _converter.Else; }
            set { _converter.Else = value; }
        }

        #endregion


        private void UpdateBindings()
        {
            if (_content != null)
            {
                if (_binding != null)
                {
                    _content.SetBinding(ContentPresenter.ContentProperty, _binding);
                }
                else
                {
                    _content.ClearValue(ContentPresenter.ContentProperty);
                }
            }
        }
    }
}
